//
//  FollowCell.m
//  JinMaJiaDemo
//
//  Created by GripMeMory on 15/9/23.
//  Copyright © 2015年 GripMeMory. All rights reserved.
//

#import "FollowCell.h"
#import <CoreText/CoreText.h>

@class FollowData;

#define kBottomLineWidth 230

#define kImageMargin 3
#define kImageWidth 142
#define kImageRightMargin 15

#define kStateLabelWidth (80 / 2)
#define kStateLabelHeight (40 / 2)

#define kTitleLabelWidth 200
#define kTitleLabelHeight 45

#define kPriceLabelWidth 200
#define kPriceLabelHeight 15

#define kStarringLabelHeight 15

#define kDurationLabelWidth 200
#define kDurationLabelHeight 25

#define kFontSize 12
#define kFontMediumSize 13
#define kFontBigSize 16

#define kButtonWidth 20

@interface FollowCell ()

{
    UIView *bottomLine;
    UIImageView *imageView;
    UIImageView *stateImageView;
    UILabel *titleLabel;
    UILabel *priceLabel;
    UILabel *starringLabel;
    NSString*foreString;
    UIColor *priceTextColor;
    NSString *foreString2;
    UILabel *durationLabel;
    UIButton *starButton;
}

@end

@implementation FollowCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
//        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        bottomLine = [[UIView alloc] init];
        bottomLine.backgroundColor = [UIColor lightGrayColor];
        
        imageView = [[UIImageView alloc] init];
        stateImageView = [[UIImageView alloc] init];
        
        titleLabel = [[UILabel alloc] init];
        titleLabel.numberOfLines = 2;
        titleLabel.font = [UIFont systemFontOfSize:kFontSize];
        
        priceLabel = [[UILabel alloc] init];
        priceLabel.textAlignment = NSTextAlignmentLeft;
        priceLabel.font = [UIFont systemFontOfSize:kFontSize];
        
        starringLabel = [[UILabel alloc] init];
        starringLabel.textAlignment = NSTextAlignmentLeft;
        starringLabel.font = [UIFont systemFontOfSize:kFontSize];
        
        
        durationLabel = [[UILabel alloc] init];
//        durationLabel.adjustsFontSizeToFitWidth = YES;
        durationLabel.textAlignment = NSTextAlignmentLeft;
        durationLabel.font = [UIFont systemFontOfSize:kFontSize];
        
        starButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [starButton setSelected:YES];
        UIImage *unselectedImage = [UIImage imageNamed:@"home_start_nosele.png"];
        UIImage *selectedImage = [UIImage imageNamed:@"home_start_issele.png"];
        [starButton setImage:selectedImage forState:UIControlStateSelected];
        [starButton setImage:unselectedImage forState:UIControlStateNormal];
        [starButton addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        
        [self.contentView addSubview:bottomLine];
        [self.contentView addSubview:imageView];
        [self.contentView addSubview:stateImageView];
        [self.contentView addSubview:titleLabel];
        [self.contentView addSubview:starringLabel];
        [self.contentView addSubview:priceLabel];
        [self.contentView addSubview:durationLabel];
        [self.contentView addSubview:starButton];
    }
    return self;
}

- (void)layoutSubviews{
    
    imageView.frame = CGRectMake(0, kImageMargin, kImageWidth, self.height - 2 * kImageMargin);
    
    bottomLine.frame = CGRectMake(imageView.right + kImageRightMargin, self.contentView.bottom - 1, kBottomLineWidth, 1);
    
    stateImageView.frame = CGRectMake(imageView.width - kStateLabelWidth, imageView.top, kStateLabelWidth, kStateLabelWidth);
    
    titleLabel.frame = CGRectMake(bottomLine.left, 0, kTitleLabelWidth, kTitleLabelHeight);
    
    priceLabel.frame = CGRectMake(bottomLine.left, titleLabel.bottom, kPriceLabelWidth, kPriceLabelHeight);
    
    starringLabel.frame = CGRectMake(bottomLine.left, priceLabel.bottom, kPriceLabelWidth, kStarringLabelHeight);
    
    durationLabel.frame = CGRectMake(bottomLine.left, starringLabel.bottom, kDurationLabelWidth, kDurationLabelHeight);
    
    starButton.frame = CGRectMake(self.right - kImageRightMargin - kButtonWidth, priceLabel.top, kButtonWidth, kButtonWidth);
}

- (void)configureCellWithModel:(HomePageModel *)model{
    [self configureStateLabelWithState:model.state];
    imageView.image = model.itemImage;
    titleLabel.text = model.title;
    starringLabel.text = [NSString stringWithFormat:@"%@次围观", model.starring];
    NSString *priceString = [NSString stringWithFormat:@"%@: ￥ %@", foreString, model.price];
    
    [priceLabel setAttributedText:[self configurePriceLabelTextAttributeWithString:priceString]];
    
    if ([foreString2 isEqualToString:@"nil"]) {
        durationLabel.text = @"";
    }else {
        [self getDifferenceWithBoundTime:model.boundTime];
    }
}

- (void)configureStateLabelWithState:(JMJFollowState)state{
    switch (state) {
        case JMJFollowStateFollowing:
            stateImageView.image = [UIImage imageNamed:@"进行中"];
            foreString = @"当前价格";
            priceTextColor = RGB_COLOR(@"#d40000");
            foreString2 = @"限时报价期";
            break;
        case JMJFollowStateEnding:
            stateImageView.image = [UIImage imageNamed:@"已结束"];
            foreString = @"最高报价";
            priceTextColor = RGB_COLOR(@"#999999");
            foreString2 = @"nil";
            break;
        case JMJFollowStateStarting:
            stateImageView.image = [UIImage imageNamed:@"尚未开始"];
            foreString = @"起始价";
            priceTextColor = RGB_COLOR(@"#d40000");
            foreString2 = @"距离拍卖还剩";
            break;
        default:
            break;
    }
}

- (NSAttributedString *)configurePriceLabelTextAttributeWithString:(NSString *)string{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    UIFont *bigFont = [UIFont systemFontOfSize:kFontBigSize];
    NSDictionary *dic = @{NSForegroundColorAttributeName:priceTextColor, NSFontAttributeName:bigFont};
    NSRange range = [string rangeOfString:@"￥"];
    [attributedString addAttributes:dic range:NSMakeRange(range.location, string.length - range.location)];
    return attributedString;
}

- (void)getDifferenceWithBoundTime:(NSString *)boundtime{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = timeFormatter;
    
    NSDate *endTime = [formatter dateFromString:boundtime];
    NSDate *nowTime = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval end = [endTime timeIntervalSince1970];
    NSTimeInterval now = [nowTime timeIntervalSince1970];
    NSTimeInterval diff = end - now;
    
    __block int timeout = (int)diff;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0)
        {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //倒计时结束
                //TODO: 修改modal followState 状态，刷新tableview，通知服务器或重新从服务器拉取数据
                durationLabel.text = @"time up";
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //更新界面
                
                if ([foreString2 isEqualToString:@"nil"]) {
                    durationLabel.text = @"";
                }else {
                    NSString *lastString = [self updateTime:timeout];
                    [durationLabel setAttributedText:[self configureDurationLabelTextAttributeWithString:lastString]];
                }
                
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);

}

- (NSString *)updateTime:(int)difference{
    
    NSString *day = @"";
    day = [NSString stringWithFormat:@"%02d", difference / 86400];
    
    difference = difference % 86400;
    
    NSString *time = [NSString stringWithFormat:@"%02d", difference / 3600];
    time = [NSString stringWithFormat:@"%@%02d", time, difference / 60 % 60];
    time = [NSString stringWithFormat:@"%@%02d",time, difference % 60 % 60];
    
    
    return [NSString stringWithFormat:@"%@%@", day, time];
}

- (NSAttributedString *)configureDurationLabelTextAttributeWithString:(NSString *)string{
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    UIFont *font = [UIFont systemFontOfSize:kFontMediumSize];
    UIColor *color = [UIColor blueColor];
    NSDictionary *dic = @{NSForegroundColorAttributeName:color, NSFontAttributeName:font};
    
    [attributedString addAttributes:dic range:NSMakeRange(0, string.length)];
    
    if ([foreString2 isEqualToString:@"nil"]) {
        durationLabel.text = @"";
    }else {
        [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:", foreString2]] atIndex:0];
        [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@"天"] atIndex:attributedString.length - 6];
        [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@"时"] atIndex:attributedString.length - 4];
        [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@"分"] atIndex:attributedString.length - 2];
        [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@"秒"] atIndex:attributedString.length];

    }
    return attributedString;
}

#pragma mark - Actions

- (void)btnClick{
    starButton.selected = !starButton.selected;
}


@end
